﻿CREATE PROCEDURE dbo.sec__CheckAccessToLoan
	(
	@LoanID int,
	@TableName varchar(128),
	@Access int = 2
	)
AS

SET NOCOUNT ON

DECLARE @Text varchar(8000),@MailTo varchar(128),@MenuID int,@MenuName varchar(128)

SET @MailTo = dbo.RegistryValue('EMail_Alert')

IF dbo.UserName() IS NULL OR (SELECT COUNT(*) FROM dbo.UserGroups()) = 0
BEGIN
	IF @@TRANCOUNT > 0 OR TRIGGER_NESTLEVEL() > 0 ROLLBACK TRANSACTION
	SET @Text = dbo.sprintf3('Access request without credentials.\nLoan - $0, Table - $1\nUserName - $2, UserGroup - $3',@LoanID,@TableName,dbo.UserName(),dbo.UserGroup())
	EXEC s_Mail @MailTo,'Security Alert (No User)',@Text
	RETURN -3
END


IF NOT EXISTS(SELECT * FROM dbo.fs_Loans_NS(@LoanID,DEFAULT,@Access))
BEGIN	
	IF @@TRANCOUNT > 0 OR TRIGGER_NESTLEVEL() > 0 ROLLBACK TRANSACTION
	SELECT @MenuName = v_Menu.MenuPath FROM t_Loan
	INNER JOIN v_Menu ON t_Loan.MenuID = v_Menu.MenuID WHERE t_Loan.ID = @LoanID
	SET @Text = dbo.sprintf5('\nAccess($4) denied or Loan $0 does not exist in $1 queue (User:$2,Group:$5,NameSpace:$3).\n',
		@LoanID,@MenuName,dbo.UserName(),dbo.UserNameSpace(),@Access,dbo.UserGroup())
	RAISERROR (@Text, 16, 1)
	SET @Text = dbo.sprintf0(@Text+'Table:$0\n',@TableName)
	EXEC s_Mail @MailTo,'Security Alert-2',@Text
	EXEC sh_SecurityLog_Add @LoanID,@Access,-2,@MenuID
	RETURN -2
END

--EXEC sh_SecurityLog_Add @LoanID,@Access,1,@MenuID

RETURN @LoanID





